<template>
  <div class="box">
    <!-- 顶部导航栏 -->
    <div class="header-container">
        <span v-if="status === 1"
              class="businessBtn">营业中</span>
      <span v-else
            class="businessBtn closing">打烊中</span>
      <div :key="restKey"
           class="right-menu">
        <div class="avatar-wrapper">
          <!--    菜单栏      -->
          <el-dropdown>
            <!--     头像       -->
            <div class="avatar-container">
              <el-avatar :size="50" fit="cover" class="custom-avatar"
                         v-if="avatar" :src="avatar"/>
              <el-avatar :size="50" fit="cover" class="custom-avatar"
                         v-else icon="el-icon-user-solid"/>
            </div>
            <el-dropdown-menu slot="dropdown" class="el-dropdown-menu">
              <el-dropdown-item @click.native="userInfo()">
                <i class="iconfont icon-icon-test35"/>
                个人信息
              </el-dropdown-item>
              <el-dropdown-item @click.native="addressInfo()">
                <i class="iconfont icon-icon-test20"/>
                地址信息
              </el-dropdown-item>
              <el-dropdown-item @click.native="updatePwd()">
                <i class="iconfont icon-mima"/>
                修改密码
              </el-dropdown-item>
              <el-dropdown-item @click.native="logout()">
                <i class="iconfont icon-tuichu"/>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>

        <div class="avatar-wrapper">
          <router-link to="/shoppingCart">
            <span class="el-dropdown-link" style="color: white;margin-top: 10px;font-size: 20px">
              <el-badge :value="num" class="item">
                <i v-if="this.num > 0" class="iconfont icon-icon-test11" style="font-size: 24px;"/>
                <i v-else class="iconfont icon-icon-test10" style="font-size: 24px;"/>
              </el-badge>
              购物车
            </span>
          </router-link>
        </div>

        <div class="avatar-wrapper">
          <router-link to="/orders">
            <span class="el-dropdown-link" style="color: white;margin-top: 10px;font-size: 20px">
              <el-badge :value="pendingPayment" class="item">
                <i class="el-icon-s-order" style="font-size: 24px;"/>
              </el-badge>
              我的订单
            </span>
          </router-link>
        </div>
      </div>
    </div>

    <!-- 个人资料弹层 -->
    <UserInfo ref="userInfoDialog" :avatar="avatar" @imageAvatarSuccess="uploadImage"/>

    <!-- 地址簿弹层 -->
    <AddressInfo ref="addressInfoDialog"/>

    <!--  修改密码弹层  -->
    <EditPwd ref="editPwdDialog"/>

    <el-container class="heightAll">
      <!--   侧边栏   -->
      <div class="aside">
        <el-aside class="el-aside">
          <div class="logo">
            <div class="sidebar-logo">
              <img src="@/assets/jindowin_w.png" style="width: 200px;height: 50px;margin-right: 100px;margin-top: 10px">
            </div>
          </div>
          <el-menu
              default-active="10"
              class="el-menu-vertical-demo"
              background-color="#545c64"
              text-color="#fff"
              active-text-color="#FFC200">
            <el-menu-item
                v-for="item in menuItems"
                :key="item.id"
                @click="setCategoryId(item.id);
              getListByCategory(item.name)"
                :index="item.id"> <!--使用 id 作为 index-->
              <span style="font-size: 18px;margin-right: 100px;">{{ item.name }}</span> <!-- 显示 name 字段 -->
            </el-menu-item>
          </el-menu>

        </el-aside>
      </div>

      <!--   表格   -->
      <el-main>
        <div class="dashboard-container">
          <div class="container">
            <div class="tableBar">
              <label style="margin-right: 20px">菜品名称:</label>
              <el-input v-model="dishName"
                        placeholder="请填写菜品名称"
                        style="width: 14%"
                        clearable
                        class="highlight-input"
                        @clear="pageQuery"/>

              <el-button style="margin-left: 20px;background: #409EFF;color: #FFFFFF"
                         @click="pageQuery">
                查询
              </el-button>

            </div>
          </div>
          <el-table v-if="tableData.length > 0"
                    :data="tableData"
                    border
                    stripe
                    class="tableBox">
            <el-table-column prop="name"
                             label="菜品名称"/>
            <el-table-column prop="image"
                             label="图片">
              <template slot-scope="{ row }">
                <el-image style="width: 40px; height: 40px; border: none; cursor: pointer"
                          :src="row.image">
                  <div slot="error"
                       class="image-slot">
                    <img src="./../../assets/noImg.png"
                         style="width: auto; height: 40px; border: none">
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="categoryName"
                             label="菜品分类"/>
            <el-table-column label="售价">
              <template slot-scope="scope">
                <span style="margin-right: 10px">￥{{ (scope.row.price).toFixed(2) * 100 / 100 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作"
                             width="250"
                             align="center">
              <template slot-scope="scope">
                <el-button type="text"
                           class="blueBug"
                           @click="selectFlavor(scope.row.id)">
                  +添加购物车
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <Empty v-if="tableData.length === 0"
                 :is-search="isSearch"/>

          <el-pagination
              class="pageList"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[10, 20, 30, 40, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>

        </div>
      </el-main>

      <!--   选择口味弹层   -->
      <el-dialog
          title="选择口味"
          :visible.sync="dialogFlavorVisible"
          width="25%"
          :show-close="false"
          :modal-append-to-body="false"
          @close="handleClose">

        <el-form :model="goodsForm" ref="goodsForm" class="demo-ruleForm">
          <label>{{ names.join(' | ') }}</label>
          <el-form-item>
            <div v-if="names.length > 1" style="margin-top: 20px">
              <el-checkbox-group v-model="dishFlavor" size="small">
                <el-checkbox-button
                    v-for="dishFlavor in dishFlavorList"
                    :key="dishFlavor"
                    :label="dishFlavor"
                    :value="dishFlavor">
                </el-checkbox-button>
              </el-checkbox-group>
            </div>
            <div v-else style="margin-top: 20px">
              <el-radio-group v-model="dishFlavor" size="small">
                <el-radio-button
                    v-for="dishFlavor in dishFlavorList"
                    :key="dishFlavor"
                    :label="dishFlavor"
                    :value="dishFlavor">
                </el-radio-button>
              </el-radio-group>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm">确认</el-button>
            <el-button @click="dialogFlavorVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

    </el-container>

  </div>
</template>


<script lang="ts">
import {Component, Vue} from 'vue-property-decorator';
import Empty from "@/components/Empty/index.vue";
import EditPwd from "@/components/EditPwd/index.vue";
import UserInfo from "@/components/UserInfo/index.vue";
import {getDishList} from "@/api/dish";
import {getList} from "@/api/category";
import {getSetmealList} from "@/api/setmeal";
import axios from "axios";
import UploadImage from "@/components/ImgUpload/index.vue";
import {addShoppingCart, getShoppingCartList, getShoppingCartSum} from "@/api/shoppingcart";
import AddressInfo from "@/components/AddressInfo/index.vue";
import {getUserInfo} from "@/api/user";
import {ordersCount} from "@/api/order";

@Component({
  components: {AddressInfo, UploadImage, UserInfo, Empty, EditPwd}
})
export default class dishView extends Vue {
  private page = 1
  private pageSize = 10
  private total = 0
  private avatar = ''
  private dishName = ''
  private categoryId = ''
  private tableData: any[] = []
  private isSearch = false
  private menuItems = []
  private restKey = 0
  private setStatus = 1
  private status = 1
  private id = ''
  private num = 0
  private pendingPayment = 0
  private names: string[] = []
  private flavors: any[] = []
  private dishFlavorList: any[] = []
  private dishFlavor = []
  private dialogFlavorVisible = false;
  private uploadImage(newImage: string) {
    this.avatar = newImage;
  }

  goodsForm = {
    dishId: '',
    setmealId: '',
    dishFlavor: ''
  } as {
    dishId: string,
    setmealId: string,
    dishFlavor: string
  }

  created() {
    this.getStatus();
    this.getUserAvatar();
    this.getShoppingCartCount();
    this.getOrders_1Count();
    this.fetchMenuItems();
    this.getListByCategory('null');
  }

  getOrders_1Count() {
    ordersCount().then(res => {
      if (res.data.code === 1) {
        this.pendingPayment = res.data.data.pendingPayment;
      }
    })
  }

  getUserAvatar() {
    getUserInfo().then(res => {
      if (res.data.code === 1) {
        this.avatar = res.data.data.avatar;
      }
    })
  }

  getShoppingCartCount() {
    getShoppingCartSum().then((res) => {
      if (res.data.code === 1) {
        this.num = res.data.data
      }
    })
  }

  handleSizeChange(pageSize: number) {
    this.pageSize = pageSize;
    this.getListByCategory('null')
  }

  handleCurrentChange(page: number) {
    this.page = page;
    this.getListByCategory('null')
  }

  setCategoryId(id: string) {
    this.categoryId = id;
  }

  getListByCategory(name) {
    const params = {
      categoryId: this.categoryId,
      page: this.page,
      pageSize: this.pageSize,
    };
    if (name.includes('套餐')) {
      getSetmealList(params).then(res => {
        this.total = res.data.data.total;
        this.tableData = res.data.data.records;
      })
    } else {
      getDishList(params).then(res => {
        this.total = res.data.data.total;
        this.tableData = res.data.data.records;
      })
    }
  }

  fetchMenuItems() {
    getList().then(res => {
      this.menuItems = res.data.data;
    })
  }

  selectFlavor(goodsId: string) {
    const tempFlavorList: string[] = [];
    const item = this.tableData.find(item => item.id === goodsId);
    let data = this.goodsForm;
    if ('flavors' in item) {
      if (item.flavors !== null && item.flavors.length > 0) {
        this.id = goodsId;
        this.names = [];
        item.flavors.forEach((flavor) => {
          this.names.push(flavor.name);
          if (flavor.value) {
            const parseFlavorValue = JSON.parse(flavor.value); // 解析成数组之后再合并
            tempFlavorList.push(...parseFlavorValue);
          }
        })
        this.dishFlavorList = tempFlavorList;
        this.dialogFlavorVisible = true;
      } else {
        data.dishId = goodsId;

        this.$confirm('确定加入购物车?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          addShoppingCart(data).then(res => {
            if (res.data.code === 1) {
              this.$message.success("添加成功!");
              this.num += 1;
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch((err) => {
            this.$message.error(err.message);
          });
        })
      }
    } else {
      data.setmealId = goodsId;
      this.$confirm('确定加入购物车?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        addShoppingCart(data).then(res => {
          if (res.data.code === 1) {
            this.$message.success("添加成功!");
            this.num += 1;
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch((err) => {
          this.$message.error(err.message);
        });
      })
    }
  }

  submitForm() {
    const data = this.goodsForm;
    data.dishId = this.id;
    data.dishFlavor = this.dishFlavor.toString();
    //alert(data.dishFlavor);

    addShoppingCart(data).then(res => {
      if (res.data.code === 1) {
        this.$message.success("添加成功!");
        this.num += 1;
        this.dialogFlavorVisible = false;
      } else {
        this.$message.error(res.data.msg);
      }
    }).catch((err) => {
      this.$message.error(err.message);
    });

  }

  addressInfo() {
    (this.$refs.addressInfoDialog as any).dialogAddressVisible = true;
  }

  userInfo() {
    (this.$refs.userInfoDialog as any).dialogVisible = true;
  }

  updatePwd() {
    (this.$refs.editPwdDialog as any).dialogFormVisible = true;  // 调用子组件中的属性
  }

  getStatus() {
    const token = sessionStorage.getItem('authentication')

    axios({
      method: "get",
      url: "/api/user/shop/status",
      headers: {
        authentication: token
      }
    }).then(res => {
      if (res.data.code === 1) {
        this.status = res.data.data
        this.setStatus = this.status
      }
    }).catch(err => {
      this.$message.error(err.message);
    })
  }

  logout() {
    this.$router.push({
      path: '/'
    })
  }

  handleClose() {
    this.dishFlavor = []
    this.dialogFlavorVisible = false;
  }
}
</script>


<style lang="scss" scoped>
.custom-avatar {
  display: flex; /* 设为 Flexbox 布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  margin: 0; /* 清除任何外边距 */
  padding: 0; /* 清除任何内边距 */
}

.avatar-container {
  width: 50px;
  height: 50px;
}

a {
  text-decoration: none;
}

.aside {
  width: 200px;
  background-color: #FFC200;
  height: 100vh;
  overflow: hidden;
  overflow-y: auto;
}

.el-aside {
  width: 200px;
  height: 100vh;
  overflow: hidden;
}

.logo {
  background-color: #FFC200; /* 设置背景颜色 */
  z-index: 1000; /* 确保它位于其他内容之上 */
  position: fixed;
}

.heightAll {
  height: 100%;
}

.el-menu-vertical-demo {
  margin-top: 53px;
  padding-top: 20px;
  height: 100%;
}

.blueBug {
  color: #419EFF !important;
  position: relative;
}

.blueBug::after {
  position: absolute;
  right: -6px;
  height: 14px;
  width: 0px;
  border-right: solid 1px #EBEEF5 !important;
}

.dashboard {
  &-container {
    margin: 60px;

    .container {
      background: #fff;
      position: relative;
      z-index: 1;
      padding: 30px 28px;
      border-radius: 4px;

      .tableBar {
        gap: 10px; /* 组件间距，也可以使用 margin */

      }

      .tableBox {
        width: 100%;
        border: 1px solid #F3F4F7;
        border-bottom: 0;
      }

      .pageList {
        text-align: center;
        margin-top: 30px;
      }

      .normal-btn {
        background: #303133;
        color: white;
        margin-left: 20px;
      }
    }
  }
}
</style>
<style scoped>

.el-dropdown-link {
  cursor: pointer;
  font-size: 15px;
  margin-top: -5px;
}

.el-icon-arrow-down {
  font-size: 20px;
  line-height: 50px;
}

.header-container {
  background: #FFC200;
  position: fixed; /* 固定在页面顶部 */
  top: 0; /* 从顶部开始 */
  left: 0; /* 从左侧开始 */
  right: 0; /* 直到右侧 */
  height: 72px; /* 设置导航栏高度，根据需求调整 */
  z-index: 1000;
}

.box {
  position: fixed;
  width: 100%;
  height: 100%;
}

.businessBtn {
  height: 20px;
  line-height: 20px;
  background: #fd3333;
  border: 1px solid #ffffff;
  border-radius: 4px;
  display: inline-block;
  padding: 0 6px;
  margin-top: 25px;
  color: #fff;


}

.closing {
  background: #606266;
}

.right-menu {
  float: right;
  margin-right: 20px;
  color: #333333;
  font-size: 14px;

  span {
    width: 130px;
    display: inline-block;
    cursor: pointer;

    &:hover {
      background: rgba(255, 255, 255, 0.52);
    }
  }

  &:focus {
    outline: none;
  }

  .avatar-wrapper {
    margin-top: 14px;
    margin-left: 18px;
    position: relative;
    float: right;
    width: 120px;
    text-align: left;
  }
}


</style>
